package util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import model.BasePage;
import model.PageInfo;
import model.PageResult;

import java.util.function.Function;

/**
 * @Desciption:
 * @author: Jacky Chai
 * @date: 2019/5/22
 */
public class PageUtil {

    public static <T> IPage<T> paramPage(int pageNo,int pageSize){
        Page<T> page =new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNo);
        return page;
    }
    public static <T> Page<T> toMybatisPlusPage(BasePage basePage) {
        Page<T> page = new Page<>();
        page.setCurrent(basePage.getPageNumber() == null ? 1 : basePage.getPageNumber());
        page.setSize(basePage.getPageSize() == null ? 10 : basePage.getPageSize());
        return page;
    }

    /**
     * page 转 pageResult
     * @param page page
     * @param mapper data实体转换function
     * @param <R>
     * @param <T>
     * @return
     */
    public static <R,T> PageResult<R> convertResult(IPage<T> page, Function<? super T, ? extends R> mapper){
        PageResult<R> pageResult = new PageResult<>();
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNo((int)page.getCurrent());
        pageInfo.setPageSize((int)page.getSize());
        pageInfo.setTotalPage((int)page.getPages());
        pageInfo.setTotalCount((int)page.getTotal());
        pageResult.setPage(pageInfo);
        pageResult.setData( ((IPage<R>)page.convert(mapper)).getRecords());
        return pageResult;
    }

}
